﻿
namespace Admin.NET.Application.Service;

/// <summary>
/// 根据枚举表生成前端的字符串常量
/// </summary>
internal class CodeGen2ConstTs
{
    public static void Create(SqlSugarRepository<BasEnum> _rep)
    {
        var listEnumType = _rep.Queryable
            .LeftJoin<BasEnumTitle>((it, title) => title.enumType == it.enumType)
            .GroupBy((it, title) => new { it.enumType, title.title })
            .Select((it, title) => new { it.enumType, title.title })
            .ToList();


        var list = _rep.Queryable
            .OrderBy(it => new { it.enumType, it.orderNo })
            .ToList();

        var enumTypeCode = "";
        var code = "";
        foreach (var item in listEnumType)
        {
            var listEnum = list.Where(it => it.enumType == item.enumType).ToList();
            var currentEnumValue = "";
            foreach (var itemEnum in listEnum)
            {
                // 添加枚举值
                if (itemEnum.code == "+" || itemEnum.code == "-")
                    currentEnumValue += string.Format(constEnumValue, "'" + itemEnum.code + "'", itemEnum.code);
                else
                    currentEnumValue += string.Format(constEnumValue, itemEnum.code, itemEnum.code);
            }
            code += string.Format(constEnum, item.enumType, currentEnumValue);

            enumTypeCode += $"  {item.enumType} = '{item.enumType}', // {item.title}\r\n";
        }

        //保存枚举类型
        var filePath = Path.Combine(GetTargetPath(), "enumType.ts");
        enumTypeCode = constEnumType + "export enum enumType {\r\n" + enumTypeCode + "};";
        File.WriteAllText(filePath, enumTypeCode);

        //保存枚举常量
        var filePath2 = Path.Combine(GetTargetPath(), "enumCode.ts");
        code = constEnumComments + "export const enumCode = {" + code + "\r\n};";
        File.WriteAllText(filePath2, code);
    }

    private static string constEnumType = @"// 枚举类型常量, 从数据库枚举表导出的, 方便前端点出来
// 执行Admin.Net.TestProject1.CodeGenTest.CreateConstFromEnum()方法即可生成此文件
";

    private static string constEnumValue = @"
		{0}: '{1}',";

    private static string constEnum = @"
	{0}: {{{1}
	}},";

    private static string constEnumComments = @"// 枚举值常量, 从数据库枚举表导出的, 方便前端点出来
// 执行Admin.Net.TestProject1.CodeGenTest.CreateConstFromEnum()方法即可生成此文件
// 由于不会实时与数据库同步,此常量字符串不能作为下拉数据源
";

    // 获取生成的文件的存放路径
    private static string GetTargetPath()
    {
        var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, "CodeGen");
        if (!Directory.Exists(backendPath))
            Directory.CreateDirectory(backendPath);
        return backendPath;
    }

}
